<template>
  <div class="category-page">
    <!-- 分类头部 -->
    <header class="category-header">
      <div class="container">
        <!-- 面包屑导航 -->
        <el-breadcrumb class="category-breadcrumb">
          <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{ categoryName }}</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 分类信息 -->
        <div class="category-info">
          <div class="category-icon" :style="{ color: categoryColor }">
            <el-icon size="48">
              <component :is="getCategoryIcon(categoryName)" />
            </el-icon>
          </div>
          <div class="category-details">
            <h1 class="category-title gradient-text">{{ categoryName }}</h1>
            <p class="category-description">{{ getCategoryDescription(categoryName) }}</p>
            <div class="category-stats">
              <span class="stat-item">
                <el-icon><Document /></el-icon>
                {{ articlesStore.articles.length }} 篇文章
              </span>
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ formatNumber(totalViews) }} 总阅读
              </span>
            </div>
          </div>
        </div>
      </div>
    </header>

    <!-- 筛选和排序 -->
    <section class="filter-section">
      <div class="container">
        <div class="filter-controls">
          <div class="sort-controls">
            <span class="control-label">排序方式：</span>
            <el-radio-group v-model="sortBy" @change="handleSortChange">
              <el-radio-button value="latest">最新发布</el-radio-button>
              <el-radio-button value="popular">最多阅读</el-radio-button>
              <el-radio-button value="trending">最多点赞</el-radio-button>
            </el-radio-group>
          </div>
          
          <div class="view-controls">
            <span class="control-label">显示方式：</span>
            <el-radio-group v-model="viewMode" @change="handleViewChange">
              <el-radio-button value="grid">网格</el-radio-button>
              <el-radio-button value="list">列表</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </div>
    </section>

    <!-- 文章列表 -->
    <section class="articles-section">
      <div class="container">
        <div 
          v-loading="articlesStore.loading"
          :class="['articles-container', `view-${viewMode}`]"
        >
          <NewsCard 
            v-for="article in sortedArticles" 
            :key="article.id"
            :article="article"
            :compact="viewMode === 'list'"
            class="article-item"
          />
        </div>

        <!-- 无内容提示 -->
        <div v-if="!articlesStore.loading && sortedArticles.length === 0" class="no-content">
          <div class="no-content-wrapper">
            <el-icon size="64"><Folder /></el-icon>
            <h3>暂无相关文章</h3>
            <p>该分类下还没有文章，请稍后再来查看。</p>
            <el-button type="primary" @click="goHome">返回首页</el-button>
          </div>
        </div>

        <!-- 加载更多 -->
        <div v-if="hasMoreArticles" class="load-more-section">
          <el-button 
            type="primary" 
            size="large" 
            @click="loadMore"
            :loading="articlesStore.loading"
            class="load-more-button"
          >
            {{ articlesStore.loading ? '加载中...' : '加载更多文章' }}
          </el-button>
        </div>
      </div>
    </section>

    <!-- 相关分类推荐 -->
    <section class="related-categories">
      <div class="container">
        <h2 class="section-title">
          <el-icon><Grid /></el-icon>
          其他分类
        </h2>
        <div class="categories-grid">
          <div 
            v-for="category in otherCategories" 
            :key="category.id"
            class="category-card glass-effect glow-hover"
            @click="goToCategory(category.id)"
          >
            <div class="category-icon" :style="{ color: category.color }">
              <el-icon size="24">
                <component :is="getCategoryIcon(category.name)" />
              </el-icon>
            </div>
            <h3 class="category-name">{{ category.name }}</h3>
            <p class="category-count">{{ category.count }} 篇</p>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Document, View, Folder, Menu } from '@element-plus/icons-vue'
import NewsCard from '@/components/NewsCard.vue'
import { useArticlesStore } from '@/stores/articles'
import { 
  formatNumber,
  getCategoryIcon,
  getCategoryColor
} from '@/utils'

const route = useRoute()
const router = useRouter()
const articlesStore = useArticlesStore()

const sortBy = ref<'latest' | 'popular' | 'trending'>('latest')
const viewMode = ref<'grid' | 'list'>('grid')

const categoryParam = computed(() => route.params.category as string)
const categoryName = computed(() => categoryParam.value)
const categoryColor = computed(() => getCategoryColor(categoryName.value))

const sortedArticles = computed(() => {
  const articles = [...articlesStore.articles]
  
  switch (sortBy.value) {
    case 'popular':
      return articles.sort((a, b) => b.readCount - a.readCount)
    case 'trending':
      return articles.sort((a, b) => b.likeCount - a.likeCount)
    case 'latest':
    default:
      return articles.sort((a, b) => b.publishTime - a.publishTime)
  }
})

const totalViews = computed(() => {
  return articlesStore.articles.reduce((total, article) => total + article.readCount, 0)
})

const hasMoreArticles = computed(() => articlesStore.hasMoreArticles)

const otherCategories = computed(() => {
  return articlesStore.categories.filter(cat => 
    cat.name !== categoryName.value
  )
})

onMounted(async () => {
  await loadCategoryArticles()
})

watch(() => route.params.category, async (newCategory) => {
  if (newCategory) {
    await loadCategoryArticles()
  }
})

const loadCategoryArticles = async () => {
  if (categoryParam.value) {
    await Promise.all([
      articlesStore.fetchArticles({ category: categoryParam.value }),
      articlesStore.initializeData() // 确保分类数据加载
    ])
  }
}

const getCategoryDescription = (category: string): string => {
  const descriptions: Record<string, string> = {
    'AI': '探索人工智能前沿技术，了解机器学习、深度学习和自然语言处理的最新进展',
    'Blockchain': '深入区块链技术世界，关注加密货币、DeFi和Web3的创新发展',
    'Hardware': '硬件科技资讯，涵盖最新的芯片技术、智能设备和电子产品',
    'Startup': '创业生态观察，分享创业故事、投资动态和商业模式创新',
    'Mobile': '移动互联网前沿，关注移动应用、5G技术和移动设备发展'
  }
  return descriptions[category] || '了解最新的科技资讯和行业动态'
}

const handleSortChange = (value: string) => {
  console.log('排序方式改变:', value)
}

const handleViewChange = (value: string) => {
  console.log('显示方式改变:', value)
}

const loadMore = async () => {
  await articlesStore.loadMoreArticles()
}

const goHome = () => {
  router.push('/')
}

const goToCategory = (categoryId: string) => {
  router.push(`/category/${categoryId}`)
}
</script>

<style scoped lang="scss">
.category-page {
  min-height: 100vh;
  background: var(--tech-bg-primary);
}

.category-header {
  padding: 40px 0 60px;
  background: linear-gradient(135deg, var(--tech-bg-secondary), var(--tech-bg-primary));
  
  .category-breadcrumb {
    margin-bottom: 32px;
    
    :deep(.el-breadcrumb__item) {
      .el-breadcrumb__inner {
        color: var(--tech-text-secondary);
        
        &:hover {
          color: var(--tech-accent-neon);
        }
      }
      
      &:last-child .el-breadcrumb__inner {
        color: var(--tech-text-primary);
      }
    }
  }
  
  .category-info {
    display: flex;
    align-items: center;
    gap: 24px;
    
    .category-icon {
      padding: 16px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 16px;
      backdrop-filter: blur(10px);
    }
    
    .category-details {
      flex: 1;
      
      .category-title {
        font-size: 36px;
        font-weight: 800;
        margin-bottom: 12px;
        letter-spacing: -0.5px;
      }
      
      .category-description {
        font-size: 16px;
        color: var(--tech-text-secondary);
        line-height: 1.6;
        margin-bottom: 16px;
        max-width: 600px;
      }
      
      .category-stats {
        display: flex;
        gap: 24px;
        
        .stat-item {
          display: flex;
          align-items: center;
          gap: 6px;
          font-size: 14px;
          color: var(--tech-text-secondary);
          
          .el-icon {
            color: var(--tech-accent-neon);
          }
        }
      }
    }
  }
}

.filter-section {
  padding: 24px 0;
  background: rgba(255, 255, 255, 0.02);
  border-bottom: 1px solid rgba(0, 212, 255, 0.1);
  
  .filter-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .sort-controls, .view-controls {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .control-label {
        font-size: 14px;
        color: var(--tech-text-secondary);
        font-weight: 500;
      }
      
      :deep(.el-radio-group) {
        .el-radio-button {
          .el-radio-button__inner {
            background: transparent;
            border: 1px solid rgba(0, 212, 255, 0.3);
            color: var(--tech-text-secondary);
            transition: all var(--tech-transition-normal) ease;
            
            &:hover {
              color: var(--tech-accent-neon);
              border-color: var(--tech-accent-neon);
            }
          }
          
          &.is-active .el-radio-button__inner {
            background: var(--tech-gradient-primary);
            border-color: var(--tech-accent-neon);
            color: white;
          }
        }
      }
    }
  }
}

.articles-section {
  padding: 40px 0;
  
  .articles-container {
    &.view-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
      gap: 24px;
    }
    
    &.view-list {
      display: flex;
      flex-direction: column;
      gap: 16px;
      
      .article-item {
        max-width: none;
      }
    }
    
    .article-item {
      animation: fadeInUp 0.5s ease forwards;
    }
  }
  
  .no-content {
    text-align: center;
    padding: 80px 20px;
    
    .no-content-wrapper {
      .el-icon {
        color: var(--tech-text-muted);
        margin-bottom: 24px;
      }
      
      h3 {
        font-size: 20px;
        color: var(--tech-text-primary);
        margin-bottom: 12px;
      }
      
      p {
        font-size: 14px;
        color: var(--tech-text-secondary);
        margin-bottom: 24px;
      }
    }
  }
  
  .load-more-section {
    text-align: center;
    padding: 40px 0;
    
    .load-more-button {
      background: var(--tech-gradient-primary);
      border: none;
      padding: 12px 32px;
      font-size: 16px;
      font-weight: 600;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(0, 212, 255, 0.3);
      }
    }
  }
}

.related-categories {
  padding: 60px 0;
  background: var(--tech-bg-secondary);
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 32px;
    color: var(--tech-text-primary);
    
    .el-icon {
      color: var(--tech-accent-neon);
    }
  }
  
  .categories-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 16px;
    
    .category-card {
      padding: 20px 16px;
      text-align: center;
      cursor: pointer;
      border-radius: 12px;
      transition: all var(--tech-transition-normal) ease;
      
      .category-icon {
        margin-bottom: 12px;
      }
      
      .category-name {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 6px;
        color: var(--tech-text-primary);
      }
      
      .category-count {
        font-size: 12px;
        color: var(--tech-text-secondary);
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .category-header {
    padding: 24px 0 40px;
    
    .category-info {
      flex-direction: column;
      text-align: center;
      gap: 16px;
      
      .category-details {
        .category-title {
          font-size: 24px;
        }
        
        .category-stats {
          justify-content: center;
          gap: 16px;
        }
      }
    }
  }
  
  .filter-section {
    .filter-controls {
      flex-direction: column;
      gap: 16px;
      align-items: flex-start;
    }
  }
  
  .articles-container {
    &.view-grid {
      grid-template-columns: 1fr;
      gap: 16px;
    }
  }
  
  .categories-grid {
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 12px;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>